import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';
import 'package:sonora/bloc/base/sj_base_bloc.dart';
import 'package:sonora/bloc/common/sj_common_event.dart';
import 'package:sonora/bloc/common/sj_common_state.dart';

@Injectable()
class SjCommonBloc extends SjBaseBloc<SjCommonEvent, SjCommonState> {
  SjCommonBloc() : super(const SjCommonState()) {
    on<SjLoadingVisibilityEmitted>(_onLoadingVisibilityEmitted);
    on<SjExceptionEmitted>(_onExceptionEmitted);
    on<SjForceLogoutButtonPressed>(_onForceLogoutButtonPressed);
  }

  FutureOr<void> _onLoadingVisibilityEmitted(
      SjLoadingVisibilityEmitted event, Emitter<SjCommonState> emit) {
    bool isLoading = state.loadingCount == 0 && event.isLoading
        ? true
        : state.loadingCount == 1 && !event.isLoading || state.loadingCount <= 0
            ? false
            : state.isLoading;
    emit(state.copyWith(isLoading: isLoading));
  }

  FutureOr<void> _onExceptionEmitted(
      SjExceptionEmitted event, Emitter<SjCommonState> emit) {
    emit(state.copyWith(appExceptionWrapper: event.appExceptionWrapper));
  }

  FutureOr<void> _onForceLogoutButtonPressed(
    SjForceLogoutButtonPressed event,
    Emitter<SjCommonState> emit,
  ) {}
}
